package top.lixunda.common.kdniao.api;

import com.google.gson.Gson;
import top.lixunda.common.kdniao.config.PropertiesConfig;
import top.lixunda.common.kdniao.entity.TrackQueryResultDTO;
import top.lixunda.common.kdniao.util.KuaiDiNiaoNetUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 快递鸟物流轨迹即时查询接口
 *
 * <p>
 * DEMO中的电商ID与私钥仅限测试使用，正式环境请单独注册账号
 * 单日超过500单查询量，建议接入我方物流轨迹订阅推送接口
 * <p>
 * ID和Key请到官网申请：http://www.kdniao.com/ServiceApply.aspx
 * @author lixunda
 */

@SuppressWarnings("WeakerAccess")
public class ApiKdniaoTrackQuery {

    /**
     * DEMO
     *
     * @param args 参数
     */
    public static void main(String[] args) {
        try {
            TrackQueryResultDTO result = ApiKdniaoTrackQuery.getOrderTracesByJson("ZTO", "75332415546288");
            System.out.print(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求url
     */
    private static final String REQ_URL = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

    /**
     * Json方式 查询订单物流轨迹
     *
     * @throws Exception Exception
     */
    public static TrackQueryResultDTO getOrderTracesByJson(String expCode, String expNo) throws Exception {
        String requestData = "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";

        Map<String, String> params = new HashMap<>(16);
        params.put("RequestData", KuaiDiNiaoNetUtil.urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", PropertiesConfig.BUSINESS_ID);
        params.put("RequestType", "1002");
        String dataSign = KuaiDiNiaoNetUtil.encrypt(requestData, PropertiesConfig.APP_KEY, "UTF-8");
        params.put("DataSign", KuaiDiNiaoNetUtil.urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");

        String result = KuaiDiNiaoNetUtil.sendPost(REQ_URL, params);
        if (result.length() > 0) {
            return new Gson().fromJson(result, TrackQueryResultDTO.class);
        }
        //根据公司业务处理返回的信息......

        return null;
    }

}
